package com.sugar.real.estate.module.business.controller.admin.apartment;

import cn.hutool.core.collection.CollUtil;
import com.sugar.real.estate.framework.apilog.core.annotation.ApiAccessLog;
import com.sugar.real.estate.framework.common.pojo.CommonResult;
import com.sugar.real.estate.framework.common.pojo.PageParam;
import com.sugar.real.estate.framework.common.pojo.PageResult;
import com.sugar.real.estate.module.business.controller.admin.apartment.vo.ApartmentPageReqVO;
import com.sugar.real.estate.module.business.controller.admin.apartment.vo.ApartmentRespVO;
import com.sugar.real.estate.module.business.controller.admin.apartment.vo.ApartmentSaveReqVO;
import com.sugar.real.estate.module.business.controller.admin.apartment.vo.ApartmentUpdateReqVO;
import com.sugar.real.estate.module.business.controller.admin.dicttype.vo.BizDictDataSimpleRespVO;
import com.sugar.real.estate.module.business.dal.dataobject.apartment.ApartmentHouseTypeDO;
import com.sugar.real.estate.module.business.dal.dataobject.apartment.ApartmentSalespersonDO;
import com.sugar.real.estate.module.business.service.apartment.ApartmentService;
import com.sugar.real.estate.module.business.service.dicttype.BizDictTypeService;
import com.sugar.real.estate.module.business.util.SelfExcelUtil;
import com.sugar.real.estate.module.infra.controller.admin.file.vo.file.FileUploadReqVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.sugar.real.estate.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static com.sugar.real.estate.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 楼盘/公寓")
@RestController
@RequestMapping("/business/apartment")
@Validated
public class ApartmentController {

    @Resource
    private ApartmentService apartmentService;
    @Resource
    private BizDictTypeService bizDictTypeService;

    @PostMapping("/create")
    @Operation(summary = "创建楼盘/公寓")
    @PreAuthorize("@ss.hasPermission('business:apartment:create')")
    public CommonResult<Long> createApartment(@Valid @RequestBody ApartmentSaveReqVO createReqVO) {
        return success(apartmentService.createApartment(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新楼盘/公寓")
    @PreAuthorize("@ss.hasPermission('business:apartment:update')")
    public CommonResult<Boolean> updateApartment(@Valid @RequestBody ApartmentSaveReqVO updateReqVO) {
        apartmentService.updateApartment(updateReqVO);
        return success(true);
    }

    @PutMapping("/update/status")
    @Operation(summary = "更新楼盘/公寓")
    @PreAuthorize("@ss.hasPermission('business:apartment:update')")
    public CommonResult<Boolean> updateApartmentStatus(@Valid @RequestBody ApartmentUpdateReqVO updateReqVO) {
        apartmentService.updateApartmentStatus(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除楼盘/公寓")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('business:apartment:delete')")
    public CommonResult<Boolean> deleteApartment(@RequestParam("id") Long id) {
        apartmentService.deleteApartment(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除楼盘/公寓")
                @PreAuthorize("@ss.hasPermission('business:apartment:delete')")
    public CommonResult<Boolean> deleteApartmentList(@RequestParam("ids") List<Long> ids) {
        apartmentService.deleteApartmentListByIds(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得楼盘/公寓")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('business:apartment:query')")
    public CommonResult<ApartmentRespVO> getApartment(@RequestParam("id") Long id) {
        return success(apartmentService.getApartment(id));
    }

    @GetMapping("/page")
    @Operation(summary = "获得楼盘/公寓分页")
    @PreAuthorize("@ss.hasPermission('business:apartment:query')")
    public CommonResult<PageResult<ApartmentRespVO>> getApartmentPage(@Valid ApartmentPageReqVO pageReqVO) {
        return success(apartmentService.getApartmentPage(pageReqVO));
    }

    @PostMapping("/import-excel")
    @Operation(summary = "导入")
    @PreAuthorize("@ss.hasPermission('business:apartment:export')")
    public CommonResult<Boolean> importApartmentExcel(FileUploadReqVO uploadReqVO) throws IOException {
        apartmentService.importApartmentExcel(uploadReqVO);
        return success(true);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出楼盘/公寓 Excel")
    @PreAuthorize("@ss.hasPermission('business:apartment:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportApartmentExcel(@Valid ApartmentPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ApartmentRespVO> list = apartmentService.getApartmentPage(pageReqVO).getList();
        List<BizDictDataSimpleRespVO> type2List = bizDictTypeService.getAllDictDataByTypeId(2L);
        Map<String, List<BizDictDataSimpleRespVO>> type2Map = type2List.stream().collect(Collectors.groupingBy(BizDictDataSimpleRespVO::getValue));
        list.forEach(apartment -> {
            List<BizDictDataSimpleRespVO> typeList = type2Map.get(apartment.getProjectType());
            if (CollUtil.isNotEmpty(typeList))
                apartment.setProjectType(typeList.get(0).getLabel());
        });
        // 导出 Excel
        SelfExcelUtil.write(response, "楼盘/公寓.xls", "数据", ApartmentRespVO.class, list);
    }

    // ==================== 子表（楼盘/公寓户型） ====================

    @GetMapping("/apartment-house-type/page")
    @Operation(summary = "获得楼盘/公寓户型分页")
    @Parameter(name = "apartmentId", description = "楼盘/公寓ID")
    @PreAuthorize("@ss.hasPermission('business:apartment:query')")
    public CommonResult<PageResult<ApartmentHouseTypeDO>> getApartmentHouseTypePage(PageParam pageReqVO,
                                                                                    @RequestParam("apartmentId") Long apartmentId) {
        return success(apartmentService.getApartmentHouseTypePage(pageReqVO, apartmentId));
    }

    @PostMapping("/apartment-house-type/create")
    @Operation(summary = "创建楼盘/公寓户型")
    @PreAuthorize("@ss.hasPermission('business:apartment:create')")
    public CommonResult<Long> createApartmentHouseType(@Valid @RequestBody ApartmentHouseTypeDO apartmentHouseType) {
        return success(apartmentService.createApartmentHouseType(apartmentHouseType));
    }

    @PutMapping("/apartment-house-type/update")
    @Operation(summary = "更新楼盘/公寓户型")
    @PreAuthorize("@ss.hasPermission('business:apartment:update')")
    public CommonResult<Boolean> updateApartmentHouseType(@Valid @RequestBody ApartmentHouseTypeDO apartmentHouseType) {
        apartmentService.updateApartmentHouseType(apartmentHouseType);
        return success(true);
    }

    @DeleteMapping("/apartment-house-type/delete")
    @Parameter(name = "id", description = "编号", required = true)
    @Operation(summary = "删除楼盘/公寓户型")
    @PreAuthorize("@ss.hasPermission('business:apartment:delete')")
    public CommonResult<Boolean> deleteApartmentHouseType(@RequestParam("id") Long id) {
        apartmentService.deleteApartmentHouseType(id);
        return success(true);
    }

    @DeleteMapping("/apartment-house-type/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除楼盘/公寓户型")
    @PreAuthorize("@ss.hasPermission('business:apartment:delete')")
    public CommonResult<Boolean> deleteApartmentHouseTypeList(@RequestParam("ids") List<Long> ids) {
        apartmentService.deleteApartmentHouseTypeListByIds(ids);
        return success(true);
    }

    @PostMapping("/apartment-house-type/import-excel")
    @Operation(summary = "导入")
    @PreAuthorize("@ss.hasPermission('business:build-house:export')")
    public CommonResult<Boolean> importExcel(FileUploadReqVO uploadReqVO, @RequestHeader("apartmentId") Long apartmentId) throws IOException {
        apartmentService.importExcel(uploadReqVO, apartmentId);
        return success(true);
    }

	@GetMapping("/apartment-house-type/get")
	@Operation(summary = "获得楼盘/公寓户型")
	@Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('business:apartment:query')")
	public CommonResult<ApartmentHouseTypeDO> getApartmentHouseType(@RequestParam("id") Long id) {
	    return success(apartmentService.getApartmentHouseType(id));
	}

    // ==================== 子表（楼盘/公寓销售人员） ====================

    @GetMapping("/apartment-salesperson/page")
    @Operation(summary = "获得楼盘/公寓销售人员分页")
    @Parameter(name = "apartmentId", description = "楼盘/公寓ID")
    @PreAuthorize("@ss.hasPermission('business:apartment:query')")
    public CommonResult<PageResult<ApartmentSalespersonDO>> getApartmentSalespersonPage(PageParam pageReqVO,
                                                                                        @RequestParam("apartmentId") Long apartmentId) {
        return success(apartmentService.getApartmentSalespersonPage(pageReqVO, apartmentId));
    }

    @PostMapping("/apartment-salesperson/create")
    @Operation(summary = "创建楼盘/公寓销售人员")
    @PreAuthorize("@ss.hasPermission('business:apartment:create')")
    public CommonResult<Long> createApartmentSalesperson(@Valid @RequestBody ApartmentSalespersonDO apartmentSalesperson) {
        return success(apartmentService.createApartmentSalesperson(apartmentSalesperson));
    }

    @PutMapping("/apartment-salesperson/update")
    @Operation(summary = "更新楼盘/公寓销售人员")
    @PreAuthorize("@ss.hasPermission('business:apartment:update')")
    public CommonResult<Boolean> updateApartmentSalesperson(@Valid @RequestBody ApartmentSalespersonDO apartmentSalesperson) {
        apartmentService.updateApartmentSalesperson(apartmentSalesperson);
        return success(true);
    }

    @DeleteMapping("/apartment-salesperson/delete")
    @Parameter(name = "id", description = "编号", required = true)
    @Operation(summary = "删除楼盘/公寓销售人员")
    @PreAuthorize("@ss.hasPermission('business:apartment:delete')")
    public CommonResult<Boolean> deleteApartmentSalesperson(@RequestParam("id") Long id) {
        apartmentService.deleteApartmentSalesperson(id);
        return success(true);
    }

    @DeleteMapping("/apartment-salesperson/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除楼盘/公寓销售人员")
    @PreAuthorize("@ss.hasPermission('business:apartment:delete')")
    public CommonResult<Boolean> deleteApartmentSalespersonList(@RequestParam("ids") List<Long> ids) {
        apartmentService.deleteApartmentSalespersonListByIds(ids);
        return success(true);
    }

	@GetMapping("/apartment-salesperson/get")
	@Operation(summary = "获得楼盘/公寓销售人员")
	@Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('business:apartment:query')")
	public CommonResult<ApartmentSalespersonDO> getApartmentSalesperson(@RequestParam("id") Long id) {
	    return success(apartmentService.getApartmentSalesperson(id));
	}

}